package com.streamer.app.adapter

import android.app.AlertDialog
import android.content.Context

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.streamer.app.R
import com.streamer.app.bean.liveProductBean
import android.widget.LinearLayout

class ProductListAdapter(
    private var products: MutableList<liveProductBean>,
    private val isOnSale: Boolean = true,
    private val onProductAction: (liveProductBean, String) -> Unit
) : RecyclerView.Adapter<ProductListAdapter.ProductViewHolder>() {

    private var context: Context? = null
    private var isShowPrise: Boolean? = true
    private var isShowSales: Boolean? = true

    // 更新商品列表数据
    fun updateProducts(
        newProducts: List<liveProductBean>, isShowPrise: Boolean = true, isShowSales: Boolean = true
    ) {
        products.clear()
        products.addAll(newProducts)
        this.isShowPrise = isShowPrise
        this.isShowSales = isShowSales
        notifyDataSetChanged()
    }


    class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ivProductImage = itemView.findViewById<ImageView>(R.id.iv_product_image)
        val tvProductCount = itemView.findViewById<TextView>(R.id.tv_product_count)
        val tvProductName = itemView.findViewById<TextView>(R.id.tv_product_name)
        val tvProductInfo = itemView.findViewById<TextView>(R.id.tv_product_info)
        val tvCurrentPrice = itemView.findViewById<TextView>(R.id.tv_current_price)
        val tvOriginalPrice = itemView.findViewById<TextView>(R.id.tv_original_price)
        val btnAction1 = itemView.findViewById<TextView>(R.id.btn_action)
        val btnAction2 = itemView.findViewById<TextView>(R.id.btn_action_1)
        val btnAction3 = itemView.findViewById<TextView>(R.id.btn_action_2)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
        context = parent.context
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_product, parent, false)
        return ProductViewHolder(view)
    }

    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        val product = products[position]

        // 设置商品信息
        holder.tvProductName.text = product.title
        if(isShowSales==true){
            holder.tvProductInfo.text = "限购${product.quota} 销量${product.salesVolume}"

        }else{
            holder.tvProductInfo.text = "限购${product.quota}"

        }
// 使用浮点数除法并格式化显示
        if (isShowPrise == true) {
            holder.tvCurrentPrice.text = "¥%.2f".format(product.price / 100.0)
            holder.tvOriginalPrice.text = "¥%.2f".format(product.originalPrice / 100.0)
        } else {
            holder.tvCurrentPrice.visibility = View.GONE
            holder.tvOriginalPrice.visibility == View.GONE
        }

        holder.tvOriginalPrice.paintFlags =
            holder.tvOriginalPrice.paintFlags or android.graphics.Paint.STRIKE_THRU_TEXT_FLAG
        holder.tvProductCount.text = (position + 1).toString() // 这里可以根据实际数据设置

        // 加载商品图片
        holder.ivProductImage.apply {
            Glide.with(this).load(product.coverImage).placeholder(R.mipmap.ic_launcher) // 占位图
                .error(R.mipmap.ic_launcher) // 错误图
                .centerCrop() // 居中裁剪
                .transform(com.bumptech.glide.load.resource.bitmap.RoundedCorners(30)) // 圆角转换
                .into(this)
        }
        // 根据商品状态设置按钮
        if (isOnSale) {
            // 售卖中状态
            holder.btnAction1.text = "下架"
            holder.btnAction1.setBackgroundResource(R.drawable.btn_gray_background)
            holder.btnAction2.text = "查看"
            holder.btnAction2.setBackgroundResource(R.drawable.btn_blue_background)
            if (product.explainStatus == 1) {
                holder.btnAction3.text = "取消讲解"
                holder.btnAction3.setBackgroundResource(R.drawable.btn_gray_background)
                holder.btnAction3.setOnClickListener {
                    onProductAction(product, "explain_cancel_product")
                }
            } else {
                holder.btnAction3.text = "讲解商品"
                holder.btnAction3.setBackgroundResource(R.drawable.btn_blue_background)
                holder.btnAction3.setOnClickListener {
                    onProductAction(product, "explain_product")
                }
            }
            holder.btnAction1.setOnClickListener {
                onProductAction(product, "take_off_shelf")
            }

            holder.btnAction2.setOnClickListener {
                onProductAction(product, "view_product")
            }
        } else {
            // 已下架状态
            holder.btnAction1.text = "上架"
            holder.btnAction1.setBackgroundResource(R.drawable.btn_blue_background)
            holder.btnAction2.text = "查看"
            holder.btnAction2.setBackgroundResource(R.drawable.btn_gray_background)


            holder.btnAction3.visibility = View.GONE

            holder.btnAction1.setOnClickListener {
                showListingTypeDialog(product)
            }

            holder.btnAction2.setOnClickListener {
                onProductAction(product, "view_product")
            }
        }
    }

    override fun getItemCount(): Int = products.size

    private fun showListingTypeDialog(product: liveProductBean) {
        context?.let { ctx ->
            val dialogView = LayoutInflater.from(ctx).inflate(R.layout.dialog_listing_type, null)
            val dialog = AlertDialog.Builder(ctx).setView(dialogView).create()

            // 设置对话框属性
            dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
            dialog.window?.setLayout(
                (ctx.resources.displayMetrics.widthPixels * 0.8).toInt(),
                ViewGroup.LayoutParams.WRAP_CONTENT
            )

            // 获取视图引用
            val rbIndirect = dialogView.findViewById<RadioButton>(R.id.rb_indirect)
            val rbLongTerm = dialogView.findViewById<RadioButton>(R.id.rb_long_term)
            val llIndirect = dialogView.findViewById<LinearLayout>(R.id.ll_indirect)
            val llLongTerm = dialogView.findViewById<LinearLayout>(R.id.ll_long_term)
            val llIndirectSettings = dialogView.findViewById<View>(R.id.ll_indirect_settings)
            val tvIndirectCount = dialogView.findViewById<TextView>(R.id.tv_indirect_count)
            val tvIndirectTime = dialogView.findViewById<TextView>(R.id.tv_indirect_time)
            val llIndirectCount = dialogView.findViewById<ConstraintLayout>(R.id.ll_indirect_count)
            val llIndirectTime = dialogView.findViewById<ConstraintLayout>(R.id.ll_indirect_time)

            // 默认选中间接
            rbIndirect.isChecked = true
            rbLongTerm.isChecked = false
            llIndirectSettings.visibility = View.VISIBLE

            // 间接选项点击
            llIndirect.setOnClickListener {
                rbIndirect.isChecked = true
                rbLongTerm.isChecked = false
                llIndirectSettings.visibility = View.VISIBLE
            }

            // 长期选项点击
            llLongTerm.setOnClickListener {
                rbLongTerm.isChecked = true
                rbIndirect.isChecked = false
                llIndirectSettings.visibility = View.GONE
            }

            // 添加RadioButton的监听器作为备用
            rbIndirect.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    rbLongTerm.isChecked = false
                    llIndirectSettings.visibility = View.VISIBLE
                }
            }

            rbLongTerm.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    rbIndirect.isChecked = false
                    llIndirectSettings.visibility = View.GONE
                }
            }

            // 间接次数选择
            llIndirectCount.setOnClickListener {
                showIndirectCountDialog(ctx) { selectedCount ->
                    tvIndirectCount.text = "${selectedCount}次"
                }
            }

            // 间接时间选择
            llIndirectTime.setOnClickListener {
                showIndirectTimeDialog(ctx) { selectedTime ->
                    tvIndirectTime.text = "${selectedTime}s"
                }
            }

            // 关闭按钮
            dialogView.findViewById<View>(R.id.iv_dialog_close).setOnClickListener {
                dialog.dismiss()
            }

            // 取消按钮
            dialogView.findViewById<TextView>(R.id.btn_dialog_cancel).setOnClickListener {
                dialog.dismiss()
            }

            // 确定按钮
            dialogView.findViewById<TextView>(R.id.btn_dialog_confirm).setOnClickListener {
                val listingType = if (rbIndirect.isChecked) "indirect" else "long_term"
                val indirectCount = tvIndirectCount.text.toString().replace("次", "")
                val indirectTime = tvIndirectTime.text.toString().replace("s", "")

                // 构建参数字符串
                val params = if (listingType == "indirect") {
                    "put_on_shelf_indirect|$indirectCount|$indirectTime"
                } else {
                    "put_on_shelf_long_term"
                }

                onProductAction(product, params)
                dialog.dismiss()
            }

            dialog.show()
        }
    }

    // 间接次数选择对话框
    private fun showIndirectCountDialog(ctx: Context, onCountSelected: (Int) -> Unit) {
        val countOptions = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
        val items = countOptions.map { "${it}次" }.toTypedArray()

        AlertDialog.Builder(ctx).setTitle("选择间接次数").setItems(items) { _, which ->
            onCountSelected(countOptions[which])
        }.show()
    }

    // 间接时间选择对话框
    private fun showIndirectTimeDialog(ctx: Context, onTimeSelected: (Int) -> Unit) {
        val timeOptions = listOf(5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60)
        val items = timeOptions.map { "${it}s" }.toTypedArray()

        AlertDialog.Builder(ctx).setTitle("选择间接时间").setItems(items) { _, which ->
            onTimeSelected(timeOptions[which])
        }.show()
    }
} 